<!DOCTYPE html>
<title>qmap</title>
<html>

	<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.css" />
	<!--[if lte IE 8]>
	<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.ie.css" />
	<![endif]-->
	<!--
	<script src="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.js"></script>
	<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
	-->

	<script src="js/leaflet.js"></script>
	<script src="js/jquery-1.9.1.min.js"></script>

	<style>
		#map {
			width: 1000px;
			height: 700px;
		}
		.info {
			padding: 6px 8px;
			font: 14px/16px Arial, Helvetica, sans-serif;
			background: white;
			background: rgba(255,255,255,0.8);
			box-shadow: 0 0 15px rgba(0,0,0,0.2);
			border-radius: 5px;
		}
		.info h4 {
			margin: 0 0 5px;
			color: #777;
		}
		.legend {
			line-height: 18px;
			color: #555;
		}
		.legend i {
			width: 18px;
			height: 18px;
			float: left;
			margin-right: 8px;
			opacity: 0.7;
		}
		.lastupdate {
			background-color: #0E73B7; /* #FFFFFF;*/
			background-image: url("images/update.png");
			background-position: 5px 5px;
			background-repeat: no-repeat;
			border-radius: 8px;
			box-shadow: 0 1px 7px rgba(0, 0, 0, 0.4);
			clear: both;
			color: #FFFFFF;
			margin-bottom: 10px;
			margin-left: 10px;
			padding: 6px 6px 6px 30px;
			z-index: 7;
			opacity:0.7;
		}
		.news-box {
			width: 700px;
			height: 80px;
			background-color: rgba(14,115,183,0.8) ;
			border-radius: 8px;
			margin-bottom: 50px;
			margin-left: 10px;
			padding: 8px 8px 8px 8px;
		}
		.news {
			background-color: #0E73B7;
			height: 70px;
			font: 24px Arial, Helvetica, sans-serif;
			background-image: url("images/stemma.png");
			background-position: 15px 10px;
			background-repeat: no-repeat;
			border-radius: 8px;
			box-shadow: 0 1px 7px rgba(0, 0, 0, 0.4);
			clear: both;
			color: #FFFFFF; /*#333333;*/
			padding: 5px 5px 5px 60px;
			z-index: 8;
			opacity:0.9;
		}
		.events-box {
			background-color: rgba(14,115,183,0.8) ;
			background-image: url("images/stemma.png");
			background-repeat: no-repeat;
			background-position: 5px 5px;
			margin-top: 10px;
			margin-right: 0px;
			color: #FFFFFF;
			border-radius: 8px;
			width: 250px;
			height: 640px;
			padding: 10px 10px 10px 10px;
			z-index: 10;
		}
		.events-title {
			font: 16px Arial, Helvetica, sans-serif;
			font-weight:bold;
			margin-left: 50px;
		}
		
		.events-title span {
			font: 14px Arial, Helvetica, sans-serif;
			margin-left:5px;
			padding:3px;
			border-radius: 8px;
			box-shadow: 0 1px 7px rgba(255, 255, 255, 0.4);
		}
		
		.events {
			height: 580px;
			margin-top: 30px;
			opacity:0.8;
			font: 14px Arial, Helvetica, sans-serif;
			background-color: #0E73B7;
			color: #FFFFFF;
			border-radius: 8px;
			box-shadow: 0 1px 7px rgba(0, 0, 0, 0.9);
			clear: both;	
			padding: 6px 6px 6px 6px;
			z-index: 11;
		}
	</style>

	<body>

		<div id="map">
			<div id="newsDiv" class="leaflet-bottom">
				<div class="news-box" >
					<div class="news" >
						Domenica blocco del traffico dalle 9 alle 17
					</div>
				</div>
			</div>
			<div id="eventsDiv" class="leaflet-top leaflet-right">
				<div class="events-box" >
					<div class="events-title">
						Comune di Brescia <span>12:11</span>
					</div>
					<div class="events"></div>
				</div>
			</div>
			<div id="lastupdateDiv" class="leaflet-bottom leaflet-left"></div>
		</div>

		<script>
			function getColor(d) {
				return d > 1000 ? '#800026' : d > 500 ? '#BD0026' : d > 200 ? '#E31A1C' : d > 100 ? '#FC4E2A' : d > 50 ? '#FD8D3C' : d > 20 ? '#FEB24C' : d > 10 ? '#FED976' : '#FFEDA0';
			}

			var map = L.map('map', {
				center : [45.5411870, 10.2194440],
				zoom : 9
			});
			
			var LOADING_STRING = "<br/><br/><br/><br/><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Loading...&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br/><br/><br/><br/><br/>";

			
			var updateTimeDiv;
			updateTimeDiv = $('.leaflet-bottom.leaflet-left');

			// BS [45.5411870, 10.2194440]
			// key leaflet    BC9A493B41014CAABB98F0471D759707
			// key personal   0FBA3CCBEEB240B8B396A762A558E0BB // UPPERCASE e c'è voluto circa 24h per averla attiva
			// 997 day
			// 999 night

			var api_server_url = "http://osm.qmap.it";
			var tile_server_url = "http://osm.qmap.it";

			//var mapUrl = tile_server_url + "/osm_tiles/{z}/{x}/{y}.png";
			var mapUrl ="http://{s}.tile.cloudmade.com/0FBA3CCBEEB240B8B396A762A558E0BB/999/256/{z}/{x}/{y}.png";
			var speedUrl = tile_server_url + "/qmap_speed/{z}/{x}/{y}.png?ts={timestamp}";
			var mapLayer = loadLayer(mapUrl);
			var speedLayer = loadLayer(speedUrl,10);

			var eventsLayer;
			eventsLayer = L.geoJson();
			/*
			var eventsMarkerGroup;
			eventsMarkerGroup = new L.MarkerClusterGroup({
				maxClusterRadius : 32,
				iconCreateFunction : function(cluster) {
					return new L.divIcon({
						html : "<b>" + cluster.getChildCount() + "</b>",
						className : 'eventCluster',
						iconSize : L.point(32, 32)
					});
				}
			});
			*/
			
			map.addLayer(mapLayer);
			map.addLayer(speedLayer);
			
			refreshLastUpdate();
			var enable_event = true;
			loadEvents();

			function loadLayer(url, z_index) {
				var attribution = 'Map data &copy; OpenStreetMap contributors';
				z_index = typeof z_index !== 'undefined' ? z_index : 1;
				//alert(z_index);
				var layer = new L.TileLayer(url, {
					minZoom : 6,
					maxZoom : 16,
					attribution : attribution,
					zIndex : z_index,
					timestamp : new Date().getTime()
				});
				return layer;
			}

			function refreshLastUpdate() {
				var url = api_server_url + '/api/lastupdate';
				$.ajax({
					url : url,
					dataType : 'jsonp',
					success : function(json) {
						updateTimeDiv.html("<div class='lastupdate'>Ultimo aggiornamento: " + json.lastUpdate.substring(0, json.lastUpdate.length - 3) + "</div>");
						//updateTraffic(json.releaseId);
					},
					error : function(jqXHR, textStatus, errorThrown) {
						updateTimeDiv.html("Errore update");
					}
				});
			}

			function loadEvents() {
				if (enable_event) {
					// if (map.hasLayer(eventsMarkerGroup)) {
					var zoom = map.getZoom();

					var eventsIconUrl = '';

					var geojsonEventOptions = {
						pointToLayer : function(feature, latlng) {

							var lcdFrom = feature.properties.lcd_from;
							var lcdTo = feature.properties.lcd_to;
							var roaLcd = feature.properties.roa_lcd;
							var ogc_fid = feature.properties.ogc_fid;
							var dir = feature.properties.dir;

							var eventTypeId = feature.properties.event_type_id;

							eventsIconUrl = api_server_url + '/api/eventicons/' + eventTypeId;
							
							var pointMarker = L.marker(latlng, {
								icon : L.icon({
									iconUrl : eventsIconUrl,
									iconSize : [25, 25],
									iconAnchor : [13, 25],
									popupAnchor : [0, -25]
								})
							});

							pointMarker.bindPopup(LOADING_STRING, options = {
								maxWidth : 500,
								autoPan : false
							});

							var url = api_server_url + '/api/event/' + ogc_fid + '/' + roaLcd + '/' + dir + '/' + lcdFrom + '/' + lcdTo;
							
							pointMarker.on('click', function(e) {
								//console.error(url);
								$.ajax({
									url : url,
									dataType : 'html',
									success : function(output) {
										$(".leaflet-popup-content").html(output);
									},
									error : function(jqXHR, textStatus, errorThrown) {
									    console.error(jqXHR);
										$(".leaflet-popup-content").html("Errore nel caricamento dati dal server: " + errorThrown);
									}
								});

							});

							return pointMarker;
						}
					};

					if (zoom >= 6) {// in pratica sempre
						/**
						 * @type LatLngBounds
						 */
						var bounds = map.getBounds();

						var url = api_server_url + '/api/events/' + zoom + '/' + bounds.toBBoxString();

						// eventsMarkerGroup.removeLayer(eventsLayer);
						$.ajax({
							url : url,
							dataType : 'jsonp',
							success : function(features) {
								eventsLayer.clearLayers();
								eventsLayer = L.geoJson(features, geojsonEventOptions);
								/*
								eventsMarkerGroup.clearLayers();
								eventsMarkerGroup.addLayer(eventsLayer);
								*/
								map.addLayer(eventsLayer);
							},
							error : function(jqXHR, textStatus, errorThrown) {
								eventsLayer.clearLayers();
							}
						});
					} else {
						eventsLayer.clearLayers();
					}
					//map.addLayer(eventsMarkerGroup);
				}

			}

			/*

			var legend = L.control({
			position : 'bottomright'
			});

			legend.onAdd = function(map) {

			var div = L.DomUtil.create('div', 'info legend'), grades = [0, 10, 20, 50, 100, 200, 500, 1000], labels = [];

			// loop through our density intervals and generate a label with a colored square for each interval
			for (var i = 0; i < grades.length; i++) {
			div.innerHTML += '<i style="background:' + getColor(grades[i] + 1) + '"></i> ' + grades[i] + (grades[i + 1] ? '&ndash;' + grades[i + 1] + '<br>' : '+');
			}

			return div;
			};

			legend.addTo(map);

			*/
			//alert(map.getZoom() +" "+ map.getBounds().toBBoxString());

		</script>

	</body>

</html>
